﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace FormsDemo1
{
    class DatabaseData
    {
        SqlConnection sc;
        public SqlConnection connect() 
        {
            string str = "Data Source=.;Initial Catalog=BookDB;User ID=sa;Password=123456;Connection Timeout = 10";//数据库连接字符串
            sc = new SqlConnection(str);//创建数据库连接对象
            sc.Open();//打开数据库连接
            return sc;//返回数据库连接对象
        }
        public  SqlCommand command(string sql) 
        {
            SqlCommand cmd = new SqlCommand(sql,connect());
            return cmd;
        }
        //更新操作
        public  int Execute(string sql) 
        {
            return command(sql).ExecuteNonQuery();
        }
        //读取操作
        public  SqlDataReader read(string sql) {
            return command(sql).ExecuteReader();
        }
        //绑定数据到dataview
        public  void bindDataToDataView(DataGridView dgv, string sql)
        {
            SqlDataAdapter adapter = new SqlDataAdapter();
            DataSet ds = new DataSet();
            adapter.SelectCommand = command(sql);
            adapter.Fill(ds);
            dgv.DataSource = ds.Tables[0];
            ds.Dispose();
        }
        //关闭数据源
        public void close() 
        {
            sc.Close();
        }
    }
}
